<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>手机投屏 - 浏览器版</title>
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background-color: #f5f5f5;
            text-align: center;
        }
        h1 {
            color: #333;
            margin-bottom: 20px;
        }
        .container {
            max-width: 900px;
            margin: 0 auto;
        }
        #video-container {
            position: relative;
            background: #000;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            margin-bottom: 20px;
        }
        video {
            max-width: 100%;
            max-height: calc(100vh - 200px);
            object-fit: contain;
        }
        .controls {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #45a049;
        }
        button:active {
            transform: scale(0.98);
        }
        #status {
            padding: 10px;
            background-color: #e8f5e9;
            border-radius: 6px;
            color: #2e7d32;
            margin-bottom: 20px;
        }
        #screenshots {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 10px;
            margin-top: 20px;
        }
        .screenshot-item {
            border: 2px solid #ddd;
            border-radius: 6px;
            overflow: hidden;
            transition: transform 0.2s;
        }
        .screenshot-item:hover {
            transform: scale(1.02);
            border-color: #4CAF50;
        }
        .screenshot-item img {
            width: 100%;
            height: auto;
            display: block;
        }
        @media (max-width: 600px) {
            .controls {
                flex-direction: column;
                align-items: center;
            }
            button {
                width: 100%;
                max-width: 300px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>手机投屏 - 浏览器版</h1>
        
        <div id="status">
            正在连接投屏服务...
        </div>
        
        <div id="video-container">
            <video id="screen" autoplay muted playsinline></video>
        </div>
        
        <div class="controls">
            <button id="start-btn">开始投屏</button>
            <button id="screenshot-btn">截图</button>
            <button id="fullscreen-btn">全屏显示</button>
            <button id="clear-btn">清除截图</button>
        </div>
        
        <h2>截图历史</h2>
        <div id="screenshots">
            <!-- 截图将显示在这里 -->
        </div>
    </div>

    <script>
        // 元素引用
        const video = document.getElementById('screen');
        const status = document.getElementById('status');
        const screenshotBtn = document.getElementById('screenshot-btn');
        const fullscreenBtn = document.getElementById('fullscreen-btn');
        const clearBtn = document.getElementById('clear-btn');
        const screenshotsDiv = document.getElementById('screenshots');
        const startBtn = document.getElementById('start-btn');
        const videoContainer = document.getElementById('video-container');
        
        // WebSocket连接
        let ws = null;
        let isConnected = false;
        
        // 初始化播放器和WebSocket
        function initPlayer() {
            // 设置HLS流地址
            const streamUrl = '/stream/stream.m3u8';
            
            // 检查浏览器是否支持HLS
            if (video.canPlayType('application/vnd.apple.mpegurl')) {
                // 原生支持HLS
                video.src = streamUrl;
                status.textContent = '投屏连接中...';
                video.addEventListener('playing', () => {
                    status.textContent = '投屏连接成功！点击屏幕可以控制手机。';
                    isConnected = true;
                    initWebSocket();
                });
                video.addEventListener('error', handleVideoError);
            } else {
                // 需要使用Hls.js库
                loadHlsLibrary(streamUrl);
            }
        }
        
        // 加载Hls.js库
        function loadHlsLibrary(streamUrl) {
            const script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/hls.js@latest';
            script.onload = () => {
                if (Hls.isSupported()) {
                    const hls = new Hls();
                    hls.loadSource(streamUrl);
                    hls.attachMedia(video);
                    hls.on(Hls.Events.MANIFEST_PARSED, () => {
                        video.play();
                        status.textContent = '投屏连接成功！点击屏幕可以控制手机。';
                        isConnected = true;
                        initWebSocket();
                    });
                    hls.on(Hls.Events.ERROR, (event, data) => {
                        console.error('HLS Error:', data);
                        status.textContent = '投屏连接失败，请检查scrcpy和ffmpeg服务是否正常运行。';
                    });
                } else {
                    status.textContent = '您的浏览器不支持HLS播放，请使用Chrome、Firefox或Safari浏览器。';
                }
            };
            script.onerror = () => {
                status.textContent = '加载HLS播放器失败，请刷新页面重试。';
            };
            document.head.appendChild(script);
        }
        
        // 初始化WebSocket连接（用于点击操作）
        function initWebSocket() {
            // 尝试连接WebSocket服务器
            try {
                const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
                const wsUrl = `${wsProtocol}//${window.location.hostname}:8765`;
                ws = new WebSocket(wsUrl);
                
                ws.onopen = () => {
                    console.log('WebSocket连接成功');
                };
                
                ws.onmessage = (event) => {
                    console.log('收到消息:', event.data);
                };
                
                ws.onclose = () => {
                    console.log('WebSocket连接关闭');
                    isConnected = false;
                    // 5秒后尝试重新连接
                    setTimeout(initWebSocket, 5000);
                };
                
                ws.onerror = (error) => {
                    console.error('WebSocket错误:', error);
                };
            } catch (e) {
                console.error('WebSocket初始化失败:', e);
                setTimeout(initWebSocket, 5000);
            }
        }
        
        // 处理视频错误
        function handleVideoError() {
            status.textContent = '视频播放错误，请检查scrcpy和ffmpeg服务是否正常运行。';
            console.error('视频错误:', video.error);
        }
        
        // 截图功能
        function takeScreenshot() {
            if (!isConnected) {
                alert('请先连接到投屏服务');
                return;
            }
            
            // 创建canvas用于截图
            const canvas = document.createElement('canvas');
            const { videoWidth, videoHeight } = video;
            canvas.width = videoWidth;
            canvas.height = videoHeight;
            
            // 绘制视频帧
            const ctx = canvas.getContext('2d');
            ctx.drawImage(video, 0, 0, videoWidth, videoHeight);
            
            // 转换为图片URL
            const imgUrl = canvas.toDataURL('image/png');
            
            // 创建截图元素
            const screenshotItem = document.createElement('div');
            screenshotItem.className = 'screenshot-item';
            
            const img = document.createElement('img');
            img.src = imgUrl;
            img.alt = '屏幕截图';
            
            // 添加下载功能
            img.onclick = () => {
                const link = document.createElement('a');
                link.href = imgUrl;
                link.download = `screenshot_${new Date().getTime()}.png`;
                link.click();
            };
            
            screenshotItem.appendChild(img);
            screenshotsDiv.prepend(screenshotItem);
            
            // 最多保留10张截图
            if (screenshotsDiv.children.length > 10) {
                screenshotsDiv.removeChild(screenshotsDiv.lastChild);
            }
        }
        
        // 处理屏幕点击事件
        function handleScreenClick(event) {
            if (!isConnected || !ws || ws.readyState !== WebSocket.OPEN) {
                return;
            }
            
            // 获取视频元素的位置和尺寸
            const rect = video.getBoundingClientRect();
            
            // 计算点击位置相对于视频的比例坐标
            const x = (event.clientX - rect.left) / rect.width;
            const y = (event.clientY - rect.top) / rect.height;
            
            // 发送点击事件到服务器
            const clickEvent = {
                type: 'click',
                x: x,
                y: y
            };
            
            ws.send(JSON.stringify(clickEvent));
        }
        
        // 全屏显示
        function toggleFullscreen() {
            if (!document.fullscreenElement) {
                videoContainer.requestFullscreen().catch(err => {
                    console.error(`全屏错误: ${err.message}`);
                });
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                }
            }
        }
        
        // 清除截图
        function clearScreenshots() {
            screenshotsDiv.innerHTML = '';
        }
        
        // 绑定事件监听
        screenshotBtn.addEventListener('click', takeScreenshot);
        fullscreenBtn.addEventListener('click', toggleFullscreen);
        clearBtn.addEventListener('click', clearScreenshots);
        startBtn.addEventListener('click', initPlayer);
        videoContainer.addEventListener('click', handleScreenClick);
        
        // 页面加载完成后初始化
        window.addEventListener('load', () => {
            // 自动尝试连接
            initPlayer();
        });
    </script>
</body>
</html>